#include "SMenuButton.h"
#include <core/StyleMgr.h>
#include <core/ImageMgr.h>
#include <QStylePainter>
#include <QMenu>
#include <QMouseEvent>

SMenuButton::SMenuButton(QWidget* parent)
	: QWidget(parent)
{

}

void SMenuButton::showMenu(QMenu* menu)
{
	menu->installEventFilter(this);
	connect(menu, &QMenu::triggered, [=]()
		{
			m_hover = false;
			update();
		});
	connect(menu, &QMenu::aboutToHide, [=]()
		{
			menu->removeEventFilter(this);
			m_hover = false;
			update();
		});
}

void SMenuButton::mousePressEvent(QMouseEvent* event)
{
	emit clicked(m_index);
	m_hover = false;
	update();
}

void SMenuButton::enterEvent(QEvent* event)
{
	m_hover = true;
	update();
	emit hovered(m_index);
}

void SMenuButton::leaveEvent(QEvent* event)
{
	QPoint pos = mapFromGlobal(QCursor::pos());
	if (!rect().contains(pos))
	{
		m_hover = false;
		update();
	}
	
}

void SMenuButton::paintEvent(QPaintEvent* event)
{
	QRect r = rect();
	QColor bkClr = StyleMgr::instance().color(m_hover ? "Hover" : "ButtonNormal");
	QStylePainter painter(this);
	painter.setPen(Qt::NoPen);
	painter.setBrush(bkClr);

	painter.drawRoundedRect(r, 2, 2);
	r.adjust(4, 0, 0, 0);
	painter.setPen(StyleMgr::instance().color("TextNormal"));
	painter.drawText(r, m_caption, QTextOption(Qt::AlignLeft | Qt::AlignVCenter));

	if (m_showMenu)
	{
		r.adjust(0, 0, -4, 0);
		SImage* img = ImgMgr::instance().image("widgets_angle_bracket_right", WidgetStatus::kNormal, devicePixelRatioF());
		if (img)
		{
			int x = r.right() - img->width();
			int y = r.center().y() - img->height() / 2;
			painter.drawImage(x, y, *img);
		}
	}
}

bool SMenuButton::eventFilter(QObject *watched, QEvent *event)
{
	if(event->type() == QEvent::MouseButtonPress)
	{
		QMouseEvent* me = dynamic_cast<QMouseEvent*>(event);
		if(rect().contains(mapFromGlobal(me->globalPos())))
		{
			emit clicked(m_index);
			m_hover = false;
			update();
		}
	}

	return QWidget::eventFilter(watched, event);
}
